﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI;
using WroxGallery.Actions;
using WroxGallery.Models.Interfaces;

namespace WroxGallery.Controllers
{

    [HandleError]
    public class AccountController : Controller
    {

        public AccountController(IFormsAuthentication formsAuth, IConfigurationRepository provider)
        {
            FormsAuth = formsAuth;
            Provider = provider;
        }

        public IFormsAuthentication FormsAuth
        {
            get;
            private set;
        }

        public IConfigurationRepository Provider
        {
            get;
            private set;
        }

        [TitleFilter("Login")]
        public ActionResult LogOn()
        {
            return View();
        }

        [TitleFilter("Login")]  
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult LogOn(string userName, string password,
            bool rememberMe, string returnUrl)
        {

            if (!ValidateLogOn(userName, password))
            {
                return View();
            }

            FormsAuth.SignIn(userName, rememberMe);
            if (!String.IsNullOrEmpty(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Admin");
            }
        }

        public ActionResult LogOff()
        {

            FormsAuth.SignOut();

            return RedirectToAction("Index", "Home");
        }

        private bool ValidateLogOn(string userName, string password)
        {
            if (String.IsNullOrEmpty(userName))
            {
                ModelState.AddModelError("username", "You must specify a username.");
            }
            if (String.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("password", "You must specify a password.");
            }
            if (!Provider.ValidateUser(userName, password))
            {
                ModelState.AddModelError("_FORM", "The username or password provided is incorrect.");
            }

            return ModelState.IsValid;
        }

    }

    public interface IFormsAuthentication
    {
        void SignIn(string userName, bool createPersistentCookie);
        void SignOut();
    }

    public class FormsAuthenticationService : IFormsAuthentication
    {
        public void SignIn(string userName, bool createPersistentCookie)
        {
            FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
        }
        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }
    }
}
